package com.example.wan1.view.todo;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.wan1.R;
import com.example.wan1.constant.Constants;
import com.example.wan1.model.TodoBean;
import com.example.wan1.utils.ToolsUtils;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.Calendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/***
 * 创建时间：2020/8/1 9:39
 * 创建人：10850
 * 功能描述：
 */
@SuppressLint("CheckResult")
public class TodoDialogFragment extends DialogFragment {
    @BindView(R.id.edit_todo_toolbar)
    Toolbar mEditTodoToolbar;
    @BindView(R.id.edit_todo_tabr_title)
    TextView mTabrTitlle;
    @BindView(R.id.edit_todo_title)
    EditText mEditTodoTitle;
    @BindView(R.id.edit_todo_content)
    EditText mEditTodoContent;
    @BindView(R.id.edit_todo_date)
    TextView mEditTodoDate;
    @BindView(R.id.edit_todo_priority)
    TextView mEditTodoPriority;
    @BindView(R.id.edit_todo_submit)
    Button mEditTodoSubmit;
    @BindView(R.id.edit_todo_type)
    TextView mEditTodoType;

    private String title;
    private TodoBean bean;
    private int mPriority;//优先级：重要、一般
    private int mTodoType;//工作1；生活2; 娱乐3；

    protected Unbinder mUnbinder;

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        RxTextView.textChanges(mEditTodoTitle).subscribe(charSequence -> {
            if (charSequence.length() > 0 && !TextUtils.isEmpty(mEditTodoContent.getText().toString())) {
                mEditTodoSubmit.setEnabled(true);
                mEditTodoSubmit.setBackgroundColor(getActivity().getColor(R.color.qc_green));
            } else {
                mEditTodoSubmit.setEnabled(false);
                mEditTodoSubmit.setBackground(getActivity().getDrawable(R.drawable.edit_bg));
            }
        });
        RxTextView.textChanges(mEditTodoContent).subscribe(charSequence -> {
            if (charSequence.length() > 0 && !TextUtils.isEmpty(mEditTodoTitle.getText().toString())) {
                mEditTodoSubmit.setEnabled(true);
                mEditTodoSubmit.setBackgroundColor(getActivity().getColor(R.color.qc_green));
            } else {
                mEditTodoSubmit.setEnabled(false);
                mEditTodoSubmit.setBackground(getActivity().getDrawable(R.drawable.edit_bg));
            }
        });

        title = getArguments().getString("title");
        if (title.equals(Constants.EDIT_TODO)) {
            bean = getArguments().getParcelable("bean");
            mTabrTitlle.setText(R.string.edit_todo);
            //对已有的值进行赋值
            mEditTodoTitle.setText(bean.getTitle());
            mEditTodoContent.setText(bean.getContent());
            mEditTodoPriority.setText(bean.getPriority() == 1 ? R.string.todo_piority_important : R.string.todo_piority_normal);
            mEditTodoDate.setText(bean.getDateStr());
            if (bean.getType() == 1) {
                mEditTodoType.setText(R.string.todo_type_work);
            } else if (bean.getType() == 2) {
                mEditTodoType.setText(R.string.todo_type_study);
            } else {
                mEditTodoType.setText(R.string.todo_type_play);
            }
            //https://blog.csdn.net/u014133119/article/details/80989479
            //android.content.res.Resources$NotFoundException: String resource ID #0x1
            //TextView不能设置int类型的内容，会报错
            mTodoType = bean.getType();
            mPriority = bean.getPriority();
        } else {
            mTabrTitlle.setText(R.string.add_todo);
            mEditTodoTitle.setText(null);
            mEditTodoContent.setText(null);
            mEditTodoPriority.setText(null);
            mEditTodoDate.setText(null);
            mEditTodoType.setText(null);
            mTodoType = 0;
            mPriority = 1;
        }

        int color = ToolsUtils.getThemeColor(getActivity());
        if (color != 0) {
            mEditTodoToolbar.setBackgroundColor(color);
//            StatusBarUtil.setColorNoTranslucent(getActivity(), color);
            //setStatusBar(color);
            //StatusBarCompat.compat(getActivity(), color);
            //setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentStyle);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_todo, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //dialogFragment全屏
        //setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreen);

        //setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentStyle);

        /*Window window = getActivity().getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);*/

        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentStyle1);

        /*//这种方式适合单独设置状态栏颜色
        Window window = getActivity().getWindow();
        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        // finally change the color
        //window.setStatusBarColor(ContextCompat.getColor(activity, R.color.my_statusbar_color));
        window.setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.orange));*/

        //StatusBarUtil.setTaskBarColored(getActivity(), ToolsUtils.getThemeColor(getActivity()));
    }

    public static TodoDialogFragment newInstance(String todoType) {
        return newInstance(todoType, null);
    }

    public static TodoDialogFragment newInstance(String todoType, TodoBean bean) {
        TodoDialogFragment fragment = new TodoDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", todoType);
        bundle.putParcelable("bean", bean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mUnbinder != null)
            mUnbinder.unbind();
    }

    @OnClick(R.id.edit_todo_date)
    public void todoDateChoose() {
        // 日期选择器，月份加一
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
                (view, year, monthOfYear, dayOfMonth) ->
                        mEditTodoDate.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth),
                Calendar.getInstance().get(Calendar.YEAR),
                Calendar.getInstance().get(Calendar.MONTH),
                Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker();
        datePickerDialog.show();
    }

    @OnClick(R.id.edit_todo_type)
    public void todoTypeChoose() {
        // 底部弹出对话框
        Dialog bottomDialog = new Dialog(getActivity(), R.style.BottomDialog);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_handle_todo, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - ToolsUtils.dp2px(16);
        params.bottomMargin = ToolsUtils.dp2px(8);
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();

        TextView t1 = contentView.findViewById(R.id.edit_todo);
        t1.setText(getString(R.string.todo_type_work));
        TextView t2 = contentView.findViewById(R.id.delete_todo);
        t2.setText(getString(R.string.todo_type_study));
        TextView t3 = contentView.findViewById(R.id.done_todo);
        t3.setText(getString(R.string.todo_type_play));
        t3.setVisibility(View.VISIBLE);

        contentView.findViewById(R.id.edit_todo).setOnClickListener(v -> {
            mTodoType = Constants.TODO_WORK_TYPE;
            mEditTodoType.setText(R.string.todo_type_work);
            bottomDialog.dismiss();
        });

        contentView.findViewById(R.id.delete_todo).setOnClickListener(v -> {
            mTodoType = Constants.TODO_STUDY_TYPE;
            mEditTodoType.setText(R.string.todo_type_study);
            bottomDialog.dismiss();
        });

        contentView.findViewById(R.id.done_todo).setOnClickListener(v -> {
            mTodoType = Constants.TODO_PLAY_TYPE;
            mEditTodoType.setText(R.string.todo_type_play);
            bottomDialog.dismiss();
        });
    }

    @OnClick(R.id.edit_todo_priority)
    public void todoPriorityChoose() {
        // 底部弹出对话框
        Dialog bottomDialog = new Dialog(getActivity(), R.style.BottomDialog);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content_circle, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - ToolsUtils.dp2px(16);
        params.bottomMargin = ToolsUtils.dp2px(8);
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        contentView.findViewById(R.id.important).setOnClickListener(v -> {
            mPriority = Constants.TODO_IMPORTANT;
            mEditTodoPriority.setText(R.string.todo_piority_important);
            bottomDialog.dismiss();
        });

        contentView.findViewById(R.id.normal).setOnClickListener(v -> {
            mPriority = Constants.TODO_NORMAL;
            mEditTodoPriority.setText(R.string.todo_piority_normal);
            bottomDialog.dismiss();
        });
    }


    @OnClick({R.id.edit_todo_iv_arrow, R.id.edit_todo_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.edit_todo_iv_arrow:
                dismiss();
                break;
            case R.id.edit_todo_submit:
                if (title.equals(Constants.EDIT_TODO)) {
                    TodoHandleTool.getInstance().updateTodo(bean.getId(), mEditTodoTitle.getText().toString(),
                            mEditTodoContent.getText().toString(), mEditTodoDate.getText().toString(),
                            bean.getStatus(), mTodoType, mPriority);
                    clearData();
                } else {
                    //如果不传时间，那么就是默认值
                    int year = Calendar.getInstance().get(Calendar.YEAR);
                    int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
                    int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
                    TodoHandleTool.getInstance().addTodo(
                            mEditTodoTitle.getText().toString(),
                            mEditTodoContent.getText().toString(),
                            TextUtils.isEmpty(mEditTodoDate.getText().toString()) ?
                                    year + "-" + month + "-" + day
                                    : mEditTodoDate.getText().toString(),
                            mTodoType, mPriority
                    );
                    clearData();
                }
                break;
        }
    }

    private void clearData() {
        mEditTodoTitle.setText(null);
        mEditTodoContent.setText(null);
        mEditTodoDate.setText(null);
        mEditTodoPriority.setText(null);
        dismiss();
    }

    /*//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected boolean useThemestatusBarColor = false;
    //是否使用状态栏文字和图标为暗色，如果状态栏采用了白色系，则需要使状态栏和图标为暗色，android6.0以上可以设置
    protected boolean useStatusBarColor = true;

    protected void setStatusBar(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getActivity().getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                //getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));//设置状态栏背景色
                getActivity().getWindow().setStatusBarColor(color);//设置状态栏背景色
            } else {
                getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);//透明
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getActivity().getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        } else {
            Toast.makeText(getActivity(), "低于4.4的android系统版本不存在沉浸式状态栏", Toast.LENGTH_SHORT).show();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && useStatusBarColor) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }*/

    //用于测试在那个生命周期方法中，是否起作用
    /*@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
        getActivity().getWindow().setStatusBarColor(Color.GREEN);
    }*/

    @Override
    public void onResume() {
        super.onResume();
        if (ToolsUtils.getNightMode(getActivity()))
            getDialog().getWindow().setStatusBarColor(Color.TRANSPARENT);
        else {
            int color = ToolsUtils.getThemeColor(getActivity());
            if (color != 0) {
                getDialog().getWindow().setStatusBarColor(color);
            }
        }
    }
}
